package com.fei.myback.service.User;

import com.fei.myback.entity.LoginUser;
import com.fei.myback.mapper.UserMapper;
import com.fei.myback.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
@Slf4j
public class UserServiceImpl implements UserService, UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public LoginUser getloginuser(String username) {
        return userMapper.getloginuser(username);
    }

    @Override
    public List<User> getusers() {
        return userMapper.getusers();
    }

    @Override
    public User getuser(String username) {
        return userMapper.getuser(username);
    }

    @Override
    public int designUser(String username, String password, String newpassword) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        LoginUser getloginuser = userMapper.getloginuser(username);
        if (getloginuser != null) {
            boolean matches = bCryptPasswordEncoder.matches(password, getloginuser.getPassword());
            if (matches){
                String encode = bCryptPasswordEncoder.encode(newpassword.trim());
                return userMapper.designUser(username,encode);
            }
        }
        return 0;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginUser user = getloginuser(username);
        if (user == null) {
//            throw new UsernameNotFoundException("该用户不存在");
            return null;
        }
        List<GrantedAuthority> set = new ArrayList<>();
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_LOGIN");
        set.add(grantedAuthority);
        user.setAuthorities(set);
        log.info("[用户实体类]: {}", grantedAuthority);
        return user;
    }

}
